from datetime import datetime

class FatigueManager(object):

    def __init__(self):
        self.delay = 0
        self.pressError = 0
        self.pressMiss = 0

        self.Threshold_Dalay = 0  #默认阈值1
        self.Threshold_PressError = 0  #默认阈值2
        self.Threshold_PressMiss = 0  #默认阈值3

    '''1、按键时延计算'''
    def calculate_pressDelay(self,beat_table):
        '''
        :param beat_table: 切完片的beat_table, 类型为dataframe
        :return:
        '''
        error = 0
        #空值处理为None
        beat_table = beat_table.fillna("None")
        for index in beat_table.index:
            '''即使是误判、漏选，也要计算时延'''
            # key = beat_table.loc[index,'beat_key']
            # res_key = beat_table.loc[index,'beat_resKey']
            #
            # if(key == res_key):
            startT_str = beat_table.loc[index,'beat_startT']
            startT = datetime.strptime(startT_str,"%Y-%m-%d %H:%M:%S")
            resp_str = beat_table.loc[index,'beat_responeT']
            resp_T = datetime.strptime(resp_str,"%Y-%m-%d %H:%M:%S")
            error += (resp_T - startT).seconds

        #总时间
        startT = datetime.strptime(beat_table.loc[0, 'beat_startT'], "%Y-%m-%d %H:%M:%S")
        endT = datetime.strptime(beat_table.loc[len(beat_table)-1, 'beat_responeT'], "%Y-%m-%d %H:%M:%S")
        totalTime = (endT - startT).seconds

        print(f"{endT} - {startT} = totalTime : {(endT - startT).seconds}")
        self.delay = error / totalTime   #时延/总时间
        return self.delay   #取均值

    '''2、按键误判计算'''
    def calculate_errorPress(self,beat_table):
        '''
        :param beat_table: 切完片的beat_table, 类型为dataframe
        :return:
        '''
        error_count = 0
        # 空值处理为None
        beat_table = beat_table.fillna("None")

        for index in beat_table.index:
            '''当不是误判，也不是漏选时，计算时延'''
            key = beat_table.loc[index, 'beat_key']
            res_key = beat_table.loc[index, 'beat_resKey']

            if (res_key != 'None' and key != res_key):
                error_count += 1

        self.pressError = error_count / len(beat_table)  #取均值
        return self.pressError

    '''3、按键漏选计算'''
    def calculate_missPress(self,beat_table):
        '''
        :param beat_table: 切完片的beat_table, 类型为dataframe
        :return:
        '''
        error_count = 0
        # 空值处理为None
        beat_table = beat_table.fillna("None")

        for index in beat_table.index:
            '''当不是误判，也不是漏选时，计算时延'''
            # key = beat_table.loc[index, 'beat_key']
            res_key = beat_table.loc[index, 'beat_resKey']

            if (res_key == "None"):
                error_count += 1

        self.pressMiss = error_count / len(beat_table) #取均值
        return self.pressMiss